﻿using dbcTools;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DBCTools.Tools
{
	public class dbcStruct
	{
		public uint RowSize;
		public byte[] StringBlock;
		public uint StringBlockSize;
		public uint ColumnCount;
		public uint RowCount;
		public bool hasPrimarykey;

		public Dictionary<uint, byte[]> dbcStore1;
		public Dictionary<uint, byte[]> dbcStort2;

		public string GetText(uint index)
		{
			if (index > StringBlock.Count())
				return "";

			ArrayList al = new ArrayList();
			while (StringBlock[index] != 0) { al.Add(StringBlock[index++]); }
			byte[] str = new byte[al.Count];
			int n = 0;
			foreach (byte o in al) { str[n++] = o; }
			return Encoding.UTF8.GetString(str); ;
		}

		public byte[] GetRow(uint entry)
		{
			if (!hasPrimarykey)
				return null;

			if (dbcStore1.ContainsKey(entry))
				return dbcStore1[entry];

			return null;
		}

		public Dictionary<uint, byte[]> GetStore()
		{
			if (hasPrimarykey)
				return dbcStore1;
			else
				return dbcStort2;
		}

		public void writeDbc(string fileName,MainWindow mw)
		{
			FileStream fs = new FileStream("outputDBC/" + fileName, FileMode.Create);
			BinaryWriter bw = new BinaryWriter(fs);
			mw.SetProBarMsg("正在写入到dbc文件中...");
			bw.Write(1128416343);
			bw.Write(RowCount);
			bw.Write(ColumnCount);
			bw.Write(RowSize);
			bw.Write(StringBlockSize);
			uint jdt = 0;
			foreach (var item in GetStore())
			{
				bw.Write(item.Value);
				mw.SetProBar((uint)((jdt++) * 100 / GetStore().Count + 1));
			}
			bw.Write(StringBlock);
			bw.Close();
			mw.SetProBarMsg("");
			mw.SetProBar(0);
		}
	}
}
